<script lang="ts" setup>
import {loginWithApp, loginWithWeapp} from '@/api/user'

const {modelValue, showWechat = true} = defineProps<{ modelValue: any, showWechat?: boolean }>()

defineEmits<{ (e: 'update:modelValue', value: boolean): void }>()

const checked = $computed(() => modelValue)

const {base, success} = useToast()
const {switchLoginState} = useUser()

// 唤起微信登录
function onWechatLogin() {
    const {base} = useToast()
    if (!checked) {
        base('请先同意用户协议！')
    } else {
        uni.login({
            provider: 'weixin',
            onlyAuthorize: true,
            success: (res) => {
                // #ifdef APP-PLUS
                onAppWechatLogin(res.code)
                // #endif
                // #ifdef MP-WEIXIN
                onWeappWechatLogin(res.code)
                // #endif
            },
            fail: () => {
                base('微信登录失败，请重试.')
            }
        })
    }
}

// APP微信登录
async function onAppWechatLogin(code: string) {
    const res = await loginWithApp(code)
    if (res.code === 0) {
        success(res.msg || '登录成功！')
        switchLoginState(res.data)
    }
}

// 小程序微信登录
async function onWeappWechatLogin(code: string) {
    const res = await loginWithWeapp(code)
    if (res.code === 0) {
        success(res.msg || '登录成功！')
        switchLoginState(res.data)
    } else {
        base(res.msg || '登录失败，请重试！')
    }
}
</script>

<template>
    <view flex-col center>
        <image v-if="showWechat" w-100 h-100 src="@/static/images/icons/common/wechat.png" @click="onWechatLogin"/>
        <view class="center mt-7.5">
            <radio :checked="checked" color="#4d555d" style="transform: scale(0.7)"
                   @click="$emit('update:modelValue', true)"/>
            <text text="24 #333333">
                同意并愿意遵守
            </text>
            <text text="24 blue">
                《隐私策略》
            </text>
            <text text="24 #333333">
                与
            </text>
            <text text="24 blue">
                《用户协议》
            </text>
        </view>
    </view>
</template>
